//
//  NSString+File.m
//  框架
//
//  Created by mayanwei on 14-9-5.
//  Copyright (c) 2014年 mayanwei. All rights reserved.
//

#import "NSString+File.h"

@implementation NSString (File)

+ (void)createDirectoryAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:path])
    {
        NSError *error = nil;
        if (![fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error])
        {
            NSString *errorMsg = [NSString stringWithFormat:@"Could not find or create directory at path '%@'.", path];
            NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:error forKey:NSUnderlyingErrorKey];
            NSException *directoryException = [NSException exceptionWithName:NSInternalInconsistencyException reason:errorMsg userInfo:errorInfo];
            
            @throw directoryException;
        }
    }
}

+ (NSString *)userDomainPathForDirectory:(NSSearchPathDirectory)searchPathDirectory pathComponent:(NSString *)pathComponent
{
    NSString *directory = [NSSearchPathForDirectoriesInDomains(searchPathDirectory, NSUserDomainMask, YES) lastObject];
    if (pathComponent)
    {
        directory = [directory stringByAppendingPathComponent:pathComponent];
    }
    
    [NSString createDirectoryAtPath:directory];
    
    return directory;
}

+ (NSString *)documentDirectory
{
    return [NSString userDomainPathForDirectory:NSDocumentDirectory pathComponent:nil];
}

+ (NSString *)documentDirectoryByAppendingPathComponent:(NSString *)pathComponent
{
    return [NSString userDomainPathForDirectory:NSDocumentDirectory pathComponent:pathComponent];
}

+ (NSString *)cacheDirectory
{
    return [NSString userDomainPathForDirectory:NSCachesDirectory pathComponent:nil];
}

+ (NSString *)cacheDirectoryByAppendingPathComponent:(NSString *)pathComponent
{
    return [self userDomainPathForDirectory:NSCachesDirectory pathComponent:pathComponent];
}

+ (NSString *)temporaryDirectory
{
    return NSTemporaryDirectory();
}

+ (NSString *)temporaryDirectoryByAppendingPathComponent:(NSString *)pathComponent
{
    NSString *directory = [NSString temporaryDirectory];
    if (pathComponent)
    {
        directory = [directory stringByAppendingPathComponent:pathComponent];
        [NSString createDirectoryAtPath:directory];
    }
    
    return directory;
}

@end
